<template>
  <view class="product-details">
    <!-- 顶部图片加搜索框 -->
    <view class="top-img-box" :style="{width: w, height: w}">
      <view class="input-box" :style="{top}" v-if="webSwiper">
				<image src="/static/icon/components/back.png" class="back" @tap="goBack" />
				<view class="search" @tap="goSearch" v-if="isShowSearch">
					<image src="/static/icon/shop/search-w.png" class="search-img" />
					<text> 搜索地点 </text>
				</view>
      </view>
      <view class="swiper" @tap="previewImg(goodsDetails.imgs)" v-if="webSwiper">
        <swiper :interval="3000" :duration="1000" :style="{width: w, height: w}" acceleration :circular="true" autoplay @change="swiperChange">
					<swiper-item v-if="goodsDetails.video_path">
						<video :src="goodsDetails.video_path" controls class="video" />
					</swiper-item>
          <swiper-item v-for="item in goodsDetails.imgs" :key="item">
            <image :src="item.url" :style="{ width: w, height: w }"/>
          </swiper-item>
        </swiper>
      </view>
			<view class="swiper-num" v-if="webSwiper"> {{swiperIndex + 1}}/{{swiperLength}} </view>
    </view>
    <view class="content">
      <!-- 基础信息 -->
      <view class="goods-info">
        <!-- 价格 -->
        <view class="prices">
          <view class="price">
            <view class="new-pri"> ￥<text>{{goodsDetails.price=='0.00'?'面议':goodsDetails.price}}</text> </view>
            <view class="old-pri"> 原价{{goodsDetails.original_price}} </view>
          </view>
          <view class="collect" @tap="isCollect">
						<view class="collect-img" :class="goodsDetails.is_collect==1?'a-collect':''"> </view>
						<view class="collect-text"> 收藏 </view>
          </view>
        </view>
        <view class="goods-title"> {{goodsDetails.name}} </view>
        <view class="goods-num">
          <view class="xl"> 销量：<text>{{goodsDetails.sales}}</text></view>
          <view class="yl"> 剩余数量：<text>{{goodsDetails.stock}}件</text></view>
        </view>
        <!-- 商家信息 -->
        <view class="merchant-info">
          <view class="merchant-name"> {{shop.name}} </view>
          <view class="phone-location">
            <view class="pl-left">
              <view class="p-num">
                <uni-icons type="phone" size="14" color="#999" />
                {{shop.help_mobile}}
              </view>
              <view class="l-info">
                <uni-icons type="location" size="14" color="#999" />
                <view class="dz"> 距您{{shop.distance}} | {{shop.detail_address}} </view>
              </view>
            </view>
            <view class="pl-right">
              <view class="item" @tap="callPhone">
                <image src="/static/icon/productDetails/phone.png" class="p-img"/>
                <text> 电话 </text>
              </view>
              <view class="item" @tap="openLoaction">
                <image src="/static/icon/productDetails/nav.png" class="p-img"/>
                <text> 导航 </text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 商品详情 -->
      <view class="goods-details">
        <view class="switch-bar">
          <view class="switch-item" :class="switchIndex==0?'a-switch-item':''" @tap="tapSwitch(0)"> 详情 </view>
          <view class="switch-item" :class="switchIndex==1?'a-switch-item':''" @tap="tapSwitch(1)"> 评价({{goodsDetails.comment_num}}) </view>
          <view class="switch-item" :class="switchIndex==2?'a-switch-item':''" @tap="tapSwitch(2)"> 推荐 </view>
        </view>
        <view class="details" id="details" v-if="switchIndex == 0">
					<view v-html="goodsDetails.detail"></view>
        </view>
        <!-- 评价 -->
				<div class="eva-list"  v-if="switchIndex == 1">
					<Evaluate @more="goEvaList" :evaList="evaList" @tapType="tapEvaType"/>
				</div>
        <!-- 推荐 -->
        <view class="reco"  v-if="switchIndex == 2">
          <view class="reco-title"> 精选推荐 </view>
					<view class="goods-list">
						<ProductItem :item="item" v-for="item in goodsList" :key="item"/>
					</view>
        </view>
      </view>
    </view>
		<!-- 底部按钮 -->
    <BtnBox 
			:num="cartNum"
			@goShop="goShop" 
			@goKF="goKF" 
			@goCart="goCart" 
			@addCart="addCart" 
			@goResult="goResult"
		/>
		<GoodsArguments 
			ref="goodsArgumentsRef" 
			:params="specParams" 
			:isPay="isPay" 
			@goPay="goPay"
			@addToCart="addMultCart"
		/>
  </view>
</template>

<script setup>
  import { computed, ref } from 'vue';
	import { onLoad, onShow, onPageScroll, onUnload } from '@dcloudio/uni-app'
	import BtnBox from './components/BtnBox.vue';
  import Evaluate from '@/components/Evaluate.vue'
  import ProductItem from '@/components/ProductItem.vue'
	import GoodsArguments from '@/components/GoodsArguments.vue';
	import { GetGoodsDetailsApi, CollectGoodsApi, AddToCartApi, GetGoodsEvaApi, GetHomeGoodsListApi } from '@/service/index.js'
	import { useAddressStore, useCartStore } from '@/store/index.js'
	import { previewImg } from '@/utils/index.js'
  const { safeArea, safeAreaInsets } = uni.getSystemInfoSync()
  const top = computed(() => safeAreaInsets.top + 3 + 'px' )
  const w = computed(() => safeArea.width + 'px' )
	const goodsArgumentsRef = ref()
  const isShowSearch = ref(false)
	const goodsSpu = ref()
	const isPay = ref(false) // 用来定义是点击了加入购物车还是去结算
	const switchIndex = ref(0)
	const goodsDetails = ref({
		imgs: [{url: ''}], //轮播图
    video_path: '',
		price: '', //价格
		original_price: '', //划线价
		name: '', //商品名称
		sales: '', //销量
		stock: '', //库存
		detail: '', // 详情
		is_collect: '' ,// 1 已收藏 0 未收藏
		shop_id: '', // 店铺id
		multi: 'true', // 是否是多规格
		comment: []
	})
	const shop = ref({
		name: '', //店铺昵称
		help_mobile: '', // 带*的商家电话
		detail_address: '', //商家地址
		help_mobile_old: '' //商家电话
	})
	const cartNum = computed(() => {
		const { cartNum } = useCartStore()
		return cartNum
	})
  const swiperIndex = ref(0)
  const swiperLength = computed(() => {
    const { imgs, video_path } = goodsDetails.value
    if(video_path) return imgs.length + 1
    return imgs.length
  })
  // 轮播图切换事件
  const swiperChange = (e) => {
    swiperIndex.value = e.detail.current
  }
	// 收藏/取消收藏
	const isCollect = () => {
		CollectGoodsApi({spu: goodsSpu.value}).then(res => {
			if(goodsDetails.value.is_collect == 1) return goodsDetails.value.is_collect = 0
			goodsDetails.value.is_collect = 1
		})
	}
	// 导航到商家
	const openLoaction = () => {
		uni.openLocation({
			name: shop.value.name,
			latitude: Number(shop.value.latitude),
			longitude: Number(shop.value.longitude),
			fail: (err) => {
        getApp().globalData.toast('打开位置失败，请稍后重试！')
			}
		})
	}
	// 获取商品评价
	const evaType = ref(1)
	const evaList = ref([])
	const getGoodsEva = () => {
		const params = {
			goods_id: goodsDetails.value.id,
			search_type: evaType.value
		}
		GetGoodsEvaApi(params).then(res => {
			evaList.value = res.data
		})
	}
	const goEvaList = () => {
		uni.navigateTo({
			url: `/pages/productDetails/EvaList?goodsId=${goodsDetails.value.id}`
		})
	}
	const tapEvaType = (e) => {
		evaType.value = e
		getGoodsEva()
	}
	// 获取推荐列表
	const goodsList = ref([])
	const getGoodsList  = () => {
		if(goodsList.value.length) return
		const { lonlat } = useAddressStore()
		const params = {
			latitude: lonlat.latitude,
			longitude: lonlat.longitude
		}
		GetHomeGoodsListApi(params).then(res => {
			goodsList.value = res.data
		})
	}
	const callPhone = () => uni.makePhoneCall({ phoneNumber: shop.value.help_mobile_old })
	const tapSwitch = (index) => {
		if(switchIndex.value == index) return
		if(index == 1) getGoodsEva()
		if(index == 2) getGoodsList()
		switchIndex.value = index
	}
  const goBack = () => uni.navigateBack()
	const goSearch = () => uni.navigateTo({ url: '/pages/search/search' })
  const goShop = () => uni.navigateTo({ url: `/pages/shop/shop?shop_id=${goodsDetails.value.shop_id}` })
	const goCart = () => uni.switchTab({ url: '/pages/shopCart/shopCart' })
	const goKF = () => {
    const { shop } = goodsDetails.value
    uni.makePhoneCall({
      phoneNumber: shop?.help_mobile_old
    })
  }
	const specParams = ref()
	// 加入购物车
	const addCart = () => {
		const { GETCARTLIST } = useCartStore()
		const { multi, skuInfo, name, restrict_num } = goodsDetails.value
		if(JSON.parse(multi)) {
      // #ifndef APP
        specParams.value = goodsDetails.value
        isPay.value = false
        setTimeout(() => {
          goodsArgumentsRef.value.open()
        }, 0)
      // #endif
      // #ifdef APP
        specNvue.value.show('slide-in-bottom',0, () => {
          uni.$emit('spec', {params: goodsDetails.value, isPay: false})
        })
      // #endif
			return
		}
		// 判断是否超出限购
		let params = { sku: goodsDetails.value.sku, num: 1 }
		AddToCartApi(params).then(res => {
			GETCARTLIST()
			getApp().globalData.toast('加入购物车成功')
		})
	}
	// 多规格商品加入购物车
  // #ifdef APP
    uni.$on('addToCar', (e) => {
      addMultCart(e.params, e.num)
    })
  // #endif
	const addMultCart = (params, num) => {
		const { GETCARTLIST } = useCartStore()
		AddToCartApi(params).then(res => {
			GETCARTLIST()
			// #ifndef APP
			  goodsArgumentsRef.value.close()
			// #endif
			// #ifdef APP
			  specNvue.value.hide('slide-out-bottom')
			// #endif
			getApp().globalData.toast('加入购物车成功')
		})
	}
  // #ifdef APP
    uni.$on('closeSpec',(e) => {
      specNvue.value.hide('slide-out-bottom')
    })
  // #endif
	// 去结算 
	const goResult = () => {
		const { multi, skuInfo, name, restrict_num } = goodsDetails.value
		// 判断是否是多规格商品
		if(JSON.parse(multi)) {
      // #ifndef APP
        specParams.value = goodsDetails.value
        isPay.value = true
        setTimeout(() => {
          goodsArgumentsRef.value.open()
        }, 0)
      // #endif
      // #ifdef APP
        specNvue.value.show('slide-in-bottom',0, () => {
          uni.$emit('spec', {params: goodsDetails.value, isPay: true})
        })
      // #endif
		} else {
			// 不是多规格商品走这里
			let params = {
				goods_item_id: skuInfo.id,
				num: restrict_num==0?1:restrict_num,
				goods_name: name
			}
			uni.navigateTo({
				url: `/pages/orderConfirm/orderConfirm?params=${JSON.stringify(params)}&shop_id=${goodsDetails.value.shop_id}`
			})
		}
	}
	// 多规格商品去结算
  // #ifdef APP
    uni.$on('goPay', (e) => {
      goPay(e.checkedSkuInfo, e.num)
    })
  // #endif
	const goPay = (goodsInfo, num) => {
		const { restrict_num, restrict_num_max } = goodsDetails.value
    // if(goodsInfo.price == '0.00') return getApp().globalData.toast('请联系商家')
		if(restrict_num!=0&&num<restrict_num) return getApp().globalData.toast('该商品'+restrict_num+'起售')
		if(restrict_num_max!=0&&num>restrict_num_max) return getApp().globalData.toast('该商品限购'+restrict_num_max)
		let params = {
			goods_item_id: goodsInfo.id,
			num,
			goods_name: goodsDetails.value.name
		}
    // #ifndef APP
      goodsArgumentsRef.value.close()
    // #endif
    // #ifdef APP
      specNvue.value.hide('slide-out-bottom')
    // #endif
		uni.navigateTo({
			url: `/pages/orderConfirm/orderConfirm?params=${JSON.stringify(params)}&shop_id=${goodsDetails.value.shop_id}`
		})
	}
	const getGoodsInfo = () => {
		const { lonlat } = useAddressStore()
		const params = {
			spu: goodsSpu.value,
			latitude: lonlat.latitude,
			longitude: lonlat.longitude
		}
		GetGoodsDetailsApi(params).then(res => {
			console.log(res);
			goodsDetails.value = res.data
			shop.value = res.data.shop
      // #ifdef APP
        uni.$emit('GoodsInfo',goodsDetails.value)
        videoNvue.value.show('none', 0, () => {
          videoNvue.value.setStyle({
            width: w.value,
            height: w.value,
            zindex: 1
          });
        })
      // #endif
		})
	}
  const videoNvue = ref()
  const searchNvue = ref()
  const specNvue = ref()
  const webSwiper = ref(false) // 是否在web端显示swiper
	onLoad((e) => {
		const { spu } = e
		goodsSpu.value = spu
		getGoodsInfo()
    // #ifdef APP
      videoNvue.value = uni.getSubNVueById('video')
      searchNvue.value = uni.getSubNVueById('search')
      specNvue.value = uni.getSubNVueById('spec')
      searchNvue.value.show('none', 0, () => {
         videoNvue.value.setStyle({ width: w.value });
       })
    // #endif
    // #ifndef APP
      webSwiper.value = true
    // #endif
	})
  onPageScroll((e) => {
    if(e.scrollTop == 0) isShowSearch.value = false
    else isShowSearch.value = true
    // #ifdef APP
      uni.$emit('search', isShowSearch.value)
    // #endif
  })
  onUnload(() => {
    // #ifdef APP
      uni.$off(['search', 'video', 'closeSpec', 'goPay', 'addToCar', 'spec'])
    // #endif
  })
</script>

<style lang="scss" scoped>
.product-details {
  padding-bottom: 58px;
  .top-img-box {
		position: relative;
    .input-box {
			position: fixed;
			padding: 0 32px 0 10px;
			display: flex;
			align-items: center;
			height: 32px;
			width: 100%;
			box-sizing: border-box;
      z-index: 9;
			.back {
				width: 28px;
				height: 28px;
				margin-right: 11px;
			}
			.search {
				flex: 1;
				height: 32px;
				font-size: 14px;
				font-weight: 400;
				color: rgba(255,255,255,0.8);
				background: rgba(255,255,255,0.3);
				border-radius: 170px;
				padding-left: 12px;
				display: flex;
				align-items: center;
				.search-img {
					width: 14px;
					height: 14px;
					margin-right: 10px;
				}
			}
    }
		.swiper {
			.video {
				width: 100%;
				height: 100%;
			}
		}
		.swiper-num {
			color: #FFFFFF;
			font-size: 12px;
			font-weight: 400;
			line-height: 11px;
			position: absolute;
			bottom: 24px;
			right: 18px;
		}
  }
  // .content {
  //   position: sticky;
  //   transform: translateY(-10px);
  //   z-index: 99999;
  // }
  // 基本信息
  .goods-info {
    background: rgba(255,255,255,0.9);
    border-radius: 10px 10px 0px 0px;
    padding: 11px;
    box-sizing: border-box;
    .prices {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      .price {
        align-items: center;
        display: flex;
        .new-pri {
          font-size: 14px;
          color: #FF3B1E;
          font-weight: bold;
          text {
            font-size: 20px;
          }
        }
        .old-pri {
          height: 11px;
          margin-left: 10px;
          font-size: 11px;
          color: #AAAAAA;
          text-decoration-line: line-through;
        }
      }
      .collect {
        display: flex;
        align-items: center;
        color: #333333;
        font-size: 12px;
				.collect-img {
					width: 20px;
					height: 20px;
					margin-right: 4px;
					background: url('/static/icon/productDetails/collect.png') no-repeat center center;
					background-size: 100% 100%;
					&.a-collect {
						background: url('/static/icon/productDetails/a-collect.png') no-repeat center center;
						background-size: 100% 100%;
					}
				}
      }
    }
    .goods-title {
      color: #222222;
      font-size: 16px;
      font-weight: bold;
      line-height: 19px;
      line-height: 19px;
    }
    .goods-num {
      display: flex;
      color: #999999;
      font-size: 12px;
      padding: 10px 0;
      font-weight: 400;
      line-height: 14px;
      border-bottom: 1px solid #EEEEEE;
      .xl, .yl {
        flex: 1;
        text {
          color: #333333;
          font-size: 12px;
        }
      }
    }
  }
  // 商家信息
  .merchant-info {
    padding-top: 10px;
    .merchant-name {
      height: 13px;
      font-size: 11px;
      color: #D68C1C;
      line-height: 13px;
    }
    .phone-location {
      display: flex;
      align-items: center;
      margin-top: 8px;
      .pl-left {
        flex: 1;
        font-size: 12px;
        color: #999999;
        .p-num {
          line-height: 19px;
        }
        .l-info {
          line-height: 19px;
          display: flex;
        }
      }
      .pl-right {
        display: flex;
        .p-img {
          width: 28px;
          height: 28px;
        }
        .item {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-right: 20px;
          margin-left: 8px;
          &:nth-last-of-type(1) {
            margin-right: 9px;
            margin-left: 0;
          }
          text {
            margin-top: 3px;
            height: 13px;
            font-size: 11px;
            color: #666666;
            line-height: 13px;
          }
        }
      }
    }
  }
  .goods-details {
    margin-top: 10px;
    .switch-bar {
      height: 40px;
      padding: 13px 0;
      background-color: #fff;
      font-size: 14px;
      color: #555555;
      display: flex;
      position: sticky;
      left: 0;
      top: 10px;
      z-index: 9;
      box-sizing: border-box;
      .switch-item {
        position: relative;
        flex: 1;
        text-align: center;
        line-height: 14px;
        &.a-switch-item {
					color: #FF3B1E;
					font-size: 16px;
					font-weight: 500;
					&::before {
					  display: block;
					  content: '';
					  position: absolute;
					  bottom: -12px;
					  left: 50%;
					  transform: translateX(-50%);
					  width: 26px;
					  height: 4px;
					  background: linear-gradient( 360deg, #FF8508 0%, #FF4847 100%);
					  border-radius: 33px;
					}
				}
      }
    }
    .details {
			:deep(img) {
				width: 100% !important;
			}
    }
  }
  .reco {
    padding: 0 12px;
    .reco-title {
      text-align: center;
      font-weight: 500;
      font-size: 14px;
      color: #333333;
      line-height: 21px;
      margin: 20px 0 10px;
    }
		.goods-list {
			columns: 2;
		}
  }
  
}
</style>
